package com.tsugun.mediaplayer.view.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.tsugun.mediaplayer.R;
import com.tsugun.mediaplayer.model.entity.MusicModel;
import com.tsugun.mediaplayer.presenter.provider.ListProvider;
import com.tsugun.mediaplayer.presenter.service.MusicAudioService;
import com.tsugun.mediaplayer.presenter.utils.ConverterHelper;
import com.tsugun.mediaplayer.presenter.utils.LogHelper;
import com.tsugun.mediaplayer.presenter.utils.SystemHelper;
import com.tsugun.mediaplayer.view.adapter.MusicItemAdapter;
import com.tsugun.mediaplayer.view.adapter.PlayListItemAdapter;
import com.tsugun.mediaplayer.view.adapter.ViewPagerAdapter;
import com.tsugun.mediaplayer.view.fragment.DownloadFragment;
import com.tsugun.mediaplayer.view.fragment.LocalFragment;
import com.tsugun.mediaplayer.view.fragment.SearchFragment;
import com.tsugun.mediaplayer.view.fragment.subfragment.FeatureFragment;
import com.tsugun.mediaplayer.view.fragment.subfragment.MyFragment;
import com.tsugun.mediaplayer.view.fragment.subfragment.SubBaseFragment;
import com.tsugun.mediaplayer.view.fragment.subfragment.TopFragment;
import com.tsugun.mediaplayer.view.loader.MediaImageLoad;
import com.tsugun.mediaplayer.view.widget.PlayListDialog;
import com.tsugun.mediaplayer.view.widget.SlidingDeformation;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.tsugun.mediaplayer.presenter.utils.ConverterHelper.*;

public class IndexActivity extends BaseActivity implements
        NavigationView.OnNavigationItemSelectedListener, SeekBar.OnSeekBarChangeListener {
    public static final String INTENT_NOTIFY_CURRENT_MUSIC = "com.tsugun.mediaplayer.current.music";

    private static final int FRAGMENT_MY = 0;
    private static final int FRAGMENT_FEATURE = 1;
    private static final int FRAGMENT_TOP = 2;
    private static final int DEFAULT_SELECT = 1; // 默认首页tab标题选择

    private static final int MSG_TIMER = 0x61; // 时间进度
    private static final int MSG_OVER = 0x60; // 结束进度条更新
    private static final int TIME_STEP = 1000; // 进度条更新频率

    // nav的头部背景
    RelativeLayout mNavHeader;
    // 主界面控件
    @BindView(R.id.id_nav_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.id_nav_view)
    NavigationView mNavView;
    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.id_view_pager)
    ViewPager mViewPager;
    @BindView(R.id.id_index_slid)
    SlidingDeformation mSDMiniPlayer;
    // 播放界面控件
    @BindView(R.id.id_content)
    RelativeLayout mRlContent;
    @BindView(R.id.id_player_toolbar)
    Toolbar mPlayerToolbar;
    @BindView(R.id.id_player_album_image)
    ImageView mIvPlayerAlbum;
    @BindView(R.id.id_player_list)
    ImageButton mIbPlayList;
    @BindView(R.id.id_player_previous)
    ImageButton mPlayerPrevious;
    @BindView(R.id.id_player_next)
    ImageButton mPlayerNext;
    @BindView(R.id.id_player_action)
    ImageButton mPlayerAction;
    @BindView(R.id.id_player_title)
    TextView mPlayerTitle;
    @BindView(R.id.id_player_sub_title)
    TextView mPlayerSubTitle;
    @BindView(R.id.id_player_favorite)
    ImageButton mPlayerFavorite;
    @BindView(R.id.id_player_mode)
    ImageButton mPlayerMode;
    @BindView(R.id.id_player_seek_bar)
    SeekBar mSBPlayer;
    @BindView(R.id.id_player_timer_left)
    TextView mTVLeft;
    @BindView(R.id.id_player_timer_right)
    TextView mTVRight;

    private PlayListDialog.Builder mDialogBuilder;

    private List<String> mTabTitle;
    private List<SubBaseFragment> mTabFragment;
    private ListProvider mProvider;
    private static ExecutorService mExecutorService = Executors.newFixedThreadPool(1); // 线程池,用于异步加载图片

    // 播放列队歌曲
    private List<MusicModel> mPlayList;
    // 萃取的颜色
    private int mGetColor;
    // Music service
    private MediaBrowserCompat mMediaBrowser;
    private MediaControllerCompat mController;
    private MediaControllerCompat.TransportControls mTransportControls;
    private MediaControllerCompat.Callback mControllerCallback;
    private int mState; // 播放状态
    private String mCurrentMusicId; // 当前播放歌曲id
    private TimerHandler mTimerHandler; // 时间播放进度handler
    private int mProgress = -1; // 当前歌曲播放进度
    private boolean isPause = false; // 是否暂停播放
    private int mMode; // 播放模式
    private boolean isSliding; // 是否正在滑动
    private boolean isSPAnimationFinish; // 动画是否结束

    private List<MusicItemAdapter> mAdapterList; // 所有歌曲列表适配器集合（用于通知更新当前播放歌曲）
    private long mLastBackTime; // 最后点击返回按钮时间

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        ButterKnife.bind(this);

        initView();
        initData();
        bindData();
        connectService();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        mNavHeader = (RelativeLayout) mNavView.getHeaderView(0);
        initPage();
        // 缓存两页
        mViewPager.setOffscreenPageLimit(2);
    }

    private void initPage() {
        if (mTabTitle != null) {
            return;
        }
        mTabTitle = new ArrayList<>();
        mTabTitle.add(getString(R.string.str_tab_my));
        mTabTitle.add(getString(R.string.str_tab_feature));
        mTabTitle.add(getString(R.string.str_tab_top));

        mTabFragment = new ArrayList<>();
        mTabFragment.add(new MyFragment());
        mTabFragment.add(new FeatureFragment());
        mTabFragment.add(new TopFragment());
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mGetColor = ContextCompat.getColor(this, R.color.grey_900);
        mTimerHandler = new TimerHandler(this);
        mState = PlaybackStateCompat.STATE_STOPPED;
        mProvider = getListProvider();
        mPlayList = new ArrayList<>();
        mMode = ConverterHelper.INSTANCE.getPLAY_MODE_LIST_LOOP();
        isSliding = false;
        isSPAnimationFinish = true;
        mAdapterList = new ArrayList<>();
    }

    /**
     * 绑定数据到控件
     */
    private void bindData() {
        setSupportActionBar(mToolbar);
        bindDrawer();
        bindPage();
        bindPlayer();
        bindLock();
    }

    /**
     * 绑定锁屏
     */
    private void bindLock() {
        IntentFilter intentFilter = new IntentFilter(LockActivity.INTENT_FILTER_CONTROL);
        registerReceiver(mReceiver, intentFilter);
    }

    /**
     * 绑定 pager
     */
    private void bindPage() {
        for (int i = 0; i < mTabTitle.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(mTabTitle.get(i)));
        }
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),
                mTabFragment, mTabTitle);
        mViewPager.setAdapter(viewPagerAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        // 设置默认选中tab
        setDefaultSelect();
    }

    /**
     * 绑定侧边栏
     */
    private void bindDrawer() {
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar,
                R.string.str_open_nav, R.string.str_close_nav);
        mDrawerLayout.addDrawerListener(toggle);
        mDrawerLayout.addDrawerListener(mDrawerListener);
        toggle.syncState();
        mNavView.setNavigationItemSelectedListener(this);
        mNavView.addOnLayoutChangeListener(mLayoutChangeListener);

    }

    /**
     * 锁定侧边栏
     */
    private void lockDrawer() {
        // 锁定侧边栏的状态，禁止修改状态
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

    /**
     * 解锁侧边栏
     */
    private void unlockDrawer() {
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
    }

    /**
     * 连接音乐服务
     */
    private void connectService() {
        MediaBrowserCompat.ConnectionCallback connectionCallback = new MusicConnectionCallback();
        // 连接音乐媒体服务
        mMediaBrowser = new MediaBrowserCompat(this, new ComponentName(this, MusicAudioService.class),
                connectionCallback, null);
        mControllerCallback = new MusicControllerCallback();
    }

    /**
     * 进度条事件
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // 拖动过程中进度条的改变
        Log.d(LogHelper.INSTANCE.getTAG(), "onProgressChanged: " + progress);
        if (fromUser) {
            mProgress = progress;
            mTVLeft.setText(ConverterHelper.INSTANCE.getConvertedTime(progress, ConverterHelper.INSTANCE.getACCURATE_TO_MINUTE()));
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // 按下进度条事件
        Log.d(LogHelper.INSTANCE.getTAG(), "onStartTrackingTouch: ");
        isPause = true;
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // 放开进度条事件
        Log.d(LogHelper.INSTANCE.getTAG(), "onStopTrackingTouch: ");
        mSBPlayer.setProgress(mProgress);
        isPause = false;
        if (mState == PlaybackStateCompat.STATE_STOPPED) {
            return;
        }
        mController.getTransportControls().seekTo(mProgress);
        // 已经暂停的话，滑动自动开始播放音乐
        if (mState == PlaybackStateCompat.STATE_PAUSED) {
            playMusic();
        }
    }

    /**
     * 播放音乐
     */
    private void playMusic() {
        if (mState != PlaybackStateCompat.STATE_PLAYING) {
            mTransportControls.play();
            mPlayerAction.setImageResource(R.drawable.ic_pause_black);
            mState = PlaybackStateCompat.STATE_PLAYING;
            return;
        }
        mTransportControls.pause();
        mPlayerAction.setImageResource(R.drawable.ic_play_arrow_black);
        mState = PlaybackStateCompat.STATE_PAUSED;
    }

    /**
     * 绑定播放界面上的控件
     */
    private void bindPlayer() {
        mSDMiniPlayer.setMOnSlidingView(mSlidingViewListener);
        // 播放界面标题栏
        mPlayerToolbar.setNavigationIcon(getDrawable(R.drawable.ic_expand_back_light));
        mPlayerToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 关闭播放界面
                if (mSDMiniPlayer.isOpen()) {
                    mSDMiniPlayer.doClose();
                }
            }
        });
        // 播放列表按钮点击事件
        mIbPlayList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createPlayListDialog();
            }
        });
        // 上一首点击事件
        mPlayerPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTransportControls.skipToPrevious();
            }
        });
        // 下一首点击事件
        mPlayerNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTransportControls.skipToNext();
            }
        });
        // 播放按钮点击事件
        mPlayerAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playClick();
            }
        });
        // 喜欢按钮点击事件
        mPlayerFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mState != PlaybackStateCompat.STATE_STOPPED) {
                    setFavoriteImage(mProvider.setFavorite(mCurrentMusicId));
                }
            }
        });
        // 播放模式点击事件
        mPlayerMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeMode();
            }
        });
        // 进度条事件处理
        mSBPlayer.setOnSeekBarChangeListener(this);
    }

    /**
     * 点击播放按钮
     */
    private void playClick() {
        if (mState != PlaybackStateCompat.STATE_PLAYING) {
            mTransportControls.play();
            mPlayerAction.setImageResource(R.drawable.ic_pause_black);
            mState = PlaybackStateCompat.STATE_PLAYING;
            return;
        }
        mTransportControls.pause();
        mPlayerAction.setImageResource(R.drawable.ic_play_arrow_black);
        mState = PlaybackStateCompat.STATE_PAUSED;
    }

    /**
     * 改变歌曲播放循环模式
     */
    private void changeMode() {
        mMode = ConverterHelper.INSTANCE.getChangedMode(mMode);
        changeModeIcon();
        Bundle bundle = new Bundle();
        bundle.putInt(MusicAudioService.Companion.getEXTRAS_MODE(), mMode);
        mTransportControls.sendCustomAction(MusicAudioService.Companion.getCUSTOM_ACTION_MODE_CHANGE(), bundle);
    }

    /**
     * 改变模式按钮图标
     */
    private void changeModeIcon() {
        if (mMode == INSTANCE.getPLAY_MODE_ONE_LOOP()) {
            mPlayerMode.setImageResource(R.drawable.ic_music_mode_loop_one);
            Toast.makeText(IndexActivity.this, R.string.str_mode_one_loop, Toast.LENGTH_SHORT).show();
            return;
        }
        if (mMode == INSTANCE.getPLAY_MODE_LIST_LOOP()) {
            mPlayerMode.setImageResource(R.drawable.ic_music_mode_one_list);
            Toast.makeText(IndexActivity.this, R.string.str_mode_list_loop, Toast.LENGTH_SHORT).show();
            return;
        }
        if (mMode == INSTANCE.getPLAY_MODE_RANDOM_LOOP()) {
            mPlayerMode.setImageResource(R.drawable.ic_music_mode_random);
            Toast.makeText(IndexActivity.this, R.string.str_mode_random, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 创建播放列表会话框
     */
    private void createPlayListDialog() {
        updatePlayList();
        final PlayListItemAdapter adapter = new PlayListItemAdapter(IndexActivity.this, mPlayList);
        mDialogBuilder = new PlayListDialog.Builder(IndexActivity.this, adapter);
        mDialogBuilder.setOnDialogClickListener(new PlayListDialog.Builder.OnDialogClickListener() {
            @Override
            public void onClearClick() {
                mPlayList.clear();
                mProvider.clearPlayList();
                mTransportControls.skipToPrevious();
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onItemClick(int position) {
                mTransportControls.skipToQueueItem(position);
            }

            @Override
            public void onDeleteClick(int position) {
                deletePlayListMusic(position);
                adapter.notifyDataSetChanged();
            }
        }).setBgColor(mGetColor).create().show();
    }

    /**
     * 删除播放列表的歌曲
     */
    public void deletePlayListMusic(int position) {
        mProvider.removePlayMusic(mPlayList.get(position).getId());
        mPlayList.remove(position);
        if (MusicAudioService.Companion.getMCurrentPosition() == position) {
            mTransportControls.skipToPrevious();
        }
    }

    /**
     * 更新播放列表
     */
    private void updatePlayList() {
        mPlayList.clear();
        mPlayList.addAll((Collection<? extends MusicModel>) mProvider.getPlayList());
    }

    /**
     * 设置默认选中的tab
     */
    private void setDefaultSelect() {
        TabLayout.Tab tab = mTabLayout.getTabAt(DEFAULT_SELECT);
        if (tab == null) {
            return;
        }
        tab.select();
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            // 发现音乐
            case R.id.id_nav_item_discover:
                break;
            // 搜索歌曲
            case R.id.id_nav_item_search:
                startFragment(new SearchFragment());
                break;
            // 本地音乐
            case R.id.id_nav_item_phone_music:
                startFragment(new LocalFragment());
                break;
            // 下载管理
            case R.id.id_nav_item_download:
                startFragment(new DownloadFragment());
                break;
            // 设置
            case R.id.id_nav_item_setting:
                Intent intent = new Intent(IndexActivity.this, SettingActivity.class);
                startActivity(intent);
                break;
            // 退出
            case R.id.id_nav_item_exit:
                finish();
                return true;
        }
        // 关闭抽屉
        mDrawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_index_toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.id_menu_search:
                startFragment(new SearchFragment());
                break;
        }
        return true;
    }

    @Override
    protected void onMusicLoadFailed() {
        // 加载数据源失败
        Log.e(LogHelper.INSTANCE.getTAG(), "onMusicLoadFailed: music search failed!!!");
        finish();
    }

    @Override
    protected void onMusicLoadComplete(ListProvider musicListProvider) {
        // 加载数据源成功
        Log.i(LogHelper.INSTANCE.getTAG(), "onMusicLoadComplete: music search complete!");
    }

    @Override
    public void onSettingChanged() {
        setSettingTheme();
        checkNightMode();
    }

    /**
     * 设置主题
     */
    private void setSettingTheme() {
        int themeColor = getThemeColor();
        ColorStateList colorStateList = new ColorStateList(new int[][]{new int[0]},
                new int[]{themeColor});
        mToolbar.setBackgroundColor(themeColor);
        mNavHeader.setBackgroundColor(themeColor);
        mPlayerAction.setBackgroundTintList(colorStateList);
        mSBPlayer.setProgressTintList(colorStateList);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!mMediaBrowser.isConnected()) {
            mMediaBrowser.connect();
        }
    }

    @Override
    public void onBackPressed() {
        // 检查子view的state
        if (checkSubView()) return;
        // 在2秒之内双击返回按钮退出
        if (checkDoubleBackTap()) return;
        // 在没有以上情况下按下返回则关闭activity
        super.onBackPressed();
        finish();
    }

    /**
     * 检测是否双击了返回
     */
    private boolean checkDoubleBackTap() {
        if (System.currentTimeMillis() - mLastBackTime > 2000) {
            mLastBackTime = System.currentTimeMillis();
            Snackbar.make(mViewPager, getString(R.string.str_back_hint), Snackbar.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    /**
     * 检查子view的state
     *
     * @return 是否关闭子view
     */
    private boolean checkSubView() {
        // 正在打开动画就不操作
        if (!isSPAnimationFinish) {
            return true;
        }
        // 播放界面展开时, 优先关闭播放界面
        if (mSDMiniPlayer.isOpen()) {
            mSDMiniPlayer.doClose();
            return true;
        }
        // 其他fragment界面打开时, 除播放界面外关闭fragment打开的界面
        if (getMusicFragmentManager().getCount() > 0) {
            getMusicFragmentManager().backFragment();
            return true;
        }
        // 如果抽屉侧边栏打开时, 则关闭侧边栏
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
            return true;
        }
        return false;
    }

    /**
     * 更新歌单列表
     */
    public void updateSheetList() {
        MyFragment myFragment = (MyFragment) mTabFragment.get(FRAGMENT_MY);
        myFragment.updateList();
    }

    @Override
    protected void onDestroy() {
        mTimerHandler.removeCallbacksAndMessages(null);
        releaseProvider();
        releaseService();
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    @Override
    public void hasFragment() {
        super.hasFragment();
        lockDrawer();
    }

    @Override
    public void noFragment() {
        super.noFragment();
        unlockDrawer();
    }

    /**
     * 销毁服务相关
     */
    private void releaseService() {
        if (mMediaBrowser.isConnected()) {
            mTransportControls.stop();
            mMediaBrowser.disconnect();
        }
        if (mController != null) {
            mController.unregisterCallback(mControllerCallback);
            mTransportControls = null;
            mController = null;
        }
    }

    /**
     * 媒体浏览服务连接状态回调接口
     */
    private class MusicConnectionCallback extends MediaBrowserCompat.ConnectionCallback {
        @Override
        public void onConnected() {
            Log.e(LogHelper.INSTANCE.getTAG(), "onConnected: connected!");
            try {
                mController = new MediaControllerCompat(IndexActivity.this,
                        mMediaBrowser.getSessionToken());
                mTransportControls = mController.getTransportControls();
                // 注册控制器回调
                mController.registerCallback(mControllerCallback);
                // 保存媒体服务控制器
                MediaControllerCompat.setMediaController(IndexActivity.this, mController);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onConnectionSuspended() {
            Log.e(LogHelper.INSTANCE.getTAG(), "onConnectionSuspended: connection suspended!");
        }

        @Override
        public void onConnectionFailed() {
            Log.e(LogHelper.INSTANCE.getTAG(), "onConnectionFailed: connection failed!");
            releaseService();
        }
    }

    /**
     * 媒体控制器状态回调接口
     */
    private class MusicControllerCallback extends MediaControllerCompat.Callback {
        @Override
        public void onSessionDestroyed() {
            super.onSessionDestroyed();
        }

        @Override
        public void onPlaybackStateChanged(PlaybackStateCompat state) {
            super.onPlaybackStateChanged(state);
            mState = state.getState();
            updateControlImage();
            sendLockScreenState();
            notifyMusicList();
        }

        @Override
        public void onMetadataChanged(MediaMetadataCompat metadata) {
            super.onMetadataChanged(metadata);
            setHandler(metadata);
            setContent(metadata);
            setTimerProgress();
            sendLockScreenBroadcast(metadata.getDescription().getMediaId());
            // 通知列表
            notifyMusicList();
        }

        @Override
        public void onQueueChanged(List<MediaSessionCompat.QueueItem> queue) {
            super.onQueueChanged(queue);
        }
    }

    /**
     * 通知所有列表更新当前播放音乐位置
     */
    private void notifyMusicList() {
        if (mDialogBuilder != null) {
            mDialogBuilder.notifyChanged();
        }
        // 移除所有已销毁的list
        mAdapterList.remove(null);
        for (MusicItemAdapter itemAdapter : mAdapterList) {
            itemAdapter.updateListItem();
        }
    }

    /**
     * 发送播放状态
     */
    private void sendLockScreenState() {
        Intent intent = new Intent(LockActivity.INTENT_FILTER_MUSIC_PLAY_STATE);
        intent.putExtra(LockActivity.EXTRA_STATE, mState);
        sendBroadcast(intent);
    }

    /**
     * 发送锁屏广播
     *
     * @param mediaId 音乐id
     */
    private void sendLockScreenBroadcast(String mediaId) {
        Log.d(LogHelper.INSTANCE.getTAG(), "sendLockScreenBroadcast: musicId=" + mediaId);
        Intent intent = new Intent(LockActivity.INTENT_FILTER_MUSIC_PLAY_INFO);
        intent.putExtra(LockActivity.EXTRA_MUSIC_ID, mediaId);
        sendBroadcast(intent);
    }

    /**
     * 更新播放控件图片
     */
    private void updateControlImage() {
        if (mState == PlaybackStateCompat.STATE_PLAYING) {
            isPause = false;
            mPlayerAction.setImageResource(R.drawable.ic_pause_black);
        } else {
            isPause = true;
            mPlayerAction.setImageResource(R.drawable.ic_play_arrow_black);
        }
    }

    /**
     * 设置迷你播放界面
     */
    private void setHandler(MediaMetadataCompat metadata) {
        int duration = (int) getMusicModel(metadata).getDuration();
        mSBPlayer.setMax(duration);
        mTVRight.setText(ConverterHelper.INSTANCE.getConvertedTime(duration, ConverterHelper.INSTANCE.getACCURATE_TO_MINUTE()));
    }

    /**
     * 设置播放界面
     */
    public void setContent(MediaMetadataCompat metadata) {
        MediaImageLoad.localImageLoad(new MusicModel(metadata), mIvPlayerAlbum);
        mPlayerTitle.setText(metadata.getDescription().getTitle());
        mPlayerSubTitle.setText(metadata.getDescription().getSubtitle());
        mCurrentMusicId = metadata.getDescription().getMediaId();
        setFavoriteImage(mProvider.isFavorite(mCurrentMusicId));
        int duration = (int) getMusicModel(metadata).getDuration();
        mSBPlayer.setMax(duration);
        mTVRight.setText(ConverterHelper.INSTANCE.getConvertedTime(duration, ConverterHelper.INSTANCE.getACCURATE_TO_MINUTE()));
        Log.d(LogHelper.INSTANCE.getTAG(), "setContent: " + mSBPlayer.getMax());
    }

    /**
     * 设置进度计时器
     */
    private void setTimerProgress() {
        // 发送消息开始更新进度
        if (mProgress == -1) {
            mTimerHandler.sendEmptyMessageDelayed(MSG_TIMER, TIME_STEP);
        }
        mProgress = 0;
        mTVLeft.setText(getString(R.string.str_timer_zero));
    }

    /**
     * 获取歌曲
     *
     * @param metadata 歌曲元数据
     * @return 歌曲
     */
    private MusicModel getMusicModel(MediaMetadataCompat metadata) {
        String musicId = metadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID);
        Log.i(LogHelper.INSTANCE.getTAG(), "setHandler: id=" + musicId);
        return mProvider.getMusic(musicId);
    }

    /**
     * 设置喜欢图片
     */
    public void setFavoriteImage(boolean isFavorite) {
        if (isFavorite) {
            mPlayerFavorite.setImageResource(R.drawable.ic_favorite_light);
        } else {
            mPlayerFavorite.setImageResource(R.drawable.ic_favorite_border_black);
        }
    }

    /**
     * 时间进度
     */
    private static class TimerHandler extends Handler {
        private WeakReference<IndexActivity> activityWeakReference;

        TimerHandler(IndexActivity indexActivity) {
            activityWeakReference = new WeakReference<>(indexActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TIMER:
                    onTimerSeek();
                    break;
                case MSG_OVER:
                    onOverSeek();
                    break;
            }
        }

        /**
         * 结束时间进度，界面恢复默认状态
         */
        private void onOverSeek() {
            IndexActivity activity = activityWeakReference.get();
            if (activity == null) {
                return;
            }
            activity.onOverPlay();
            Log.d(LogHelper.INSTANCE.getTAG(), "onOverSeek: Over!!!");
        }

        /**
         * 时间进度向前移动
         */
        private void onTimerSeek() {
            IndexActivity activity = activityWeakReference.get();
            if (activity == null) {
                return;
            }
            // 检测后台服务是否停止播放音频
            if (activity.mController.getPlaybackState().getState() == PlaybackStateCompat.STATE_STOPPED) {
                activity.mTimerHandler.sendEmptyMessage(MSG_OVER);
                return;
            }
            if (activity.isPause) {
                activity.mTimerHandler.sendEmptyMessageDelayed(MSG_TIMER, TIME_STEP);
                return;
            }
            activity.mProgress += TIME_STEP;
            Log.d(LogHelper.INSTANCE.getTAG(), "onTimerSeek: progress=" + activity.mProgress);
            // 正在滑动操作时放弃更新界面控件
            if (!activity.isSliding && activity.isSPAnimationFinish) {
                updateInterface(activity);
            }
            // 每秒发送一次消息
            activity.mTimerHandler.sendEmptyMessageDelayed(MSG_TIMER, TIME_STEP);
        }

        /**
         * 更新界面
         */
        private void updateInterface(IndexActivity activity) {
            int maxProgress = activity.mSBPlayer.getMax();
            if (maxProgress < activity.mProgress) {
                activity.mSBPlayer.setProgress(maxProgress);
                activity.mTVLeft.setText(ConverterHelper.INSTANCE.getConvertedTime(maxProgress,
                        ConverterHelper.INSTANCE.getACCURATE_TO_MINUTE()));
            } else {
                activity.mSBPlayer.setProgress(activity.mProgress);
                activity.mTVLeft.setText(ConverterHelper.INSTANCE.getConvertedTime(activity.mProgress,
                        ConverterHelper.INSTANCE.getACCURATE_TO_MINUTE()));
            }
        }
    }

    /**
     * 结束播放后的界面更新
     */
    private void onOverPlay() {
        mProgress = -1;
        mState = PlaybackStateCompat.STATE_STOPPED;
        // 最大化播放控件界面恢复
        mSBPlayer.setProgress(0);
        mSBPlayer.setMax(0);
        mPlayerTitle.setText(R.string.app_name);
        mPlayerSubTitle.setText(R.string.app_name);
        mPlayerFavorite.setImageResource(R.drawable.ic_favorite_border_black);
        mTVLeft.setText(R.string.str_timer_zero);
        mTVRight.setText(R.string.str_timer_zero);
        mIvPlayerAlbum.setImageResource(R.drawable.ic_music_default);
    }

    /**
     * 侧边栏滑动变化事件监听
     */
    private DrawerLayout.DrawerListener mDrawerListener = new DrawerLayout.DrawerListener() {
        private boolean isGone = false;

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            if (slideOffset != 0 && !isGone) {
                mSDMiniPlayer.setVisibility(View.GONE);
                isGone = true;
            }
            if (slideOffset == 0) {
                mSDMiniPlayer.setVisibility(View.VISIBLE);
                isGone = false;
            }
        }

        @Override
        public void onDrawerOpened(View drawerView) {
        }

        @Override
        public void onDrawerClosed(View drawerView) {
        }

        @Override
        public void onDrawerStateChanged(int newState) {
        }
    };

    /**
     * 侧边栏变化事件监听
     */
    private View.OnLayoutChangeListener mLayoutChangeListener = new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                   int oldLeft, int oldTop, int oldRight, int oldBottom) {
//                SettingPreferenceHelper.setNightDrawer(v, IndexActivity.this);
            onSettingChanged();
        }
    };

    /**
     * 播放界面的滑动事件监听
     */
    private SlidingDeformation.OnSlidingView mSlidingViewListener = new SlidingDeformation.OnSlidingView() {
        @Override
        public void onTouchDown() {
            isSliding = true;
        }

        @Override
        public void onTouchUp() {
        }

        @Override
        public void startAnimation() {
            isSPAnimationFinish = false;
        }

        @Override
        public void endAnimation() {
            isSliding = false;
            isSPAnimationFinish = true;
        }
    };

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String extra = intent.getStringExtra(LockActivity.EXTRA_CONTROL);
            switch (extra) {
                case LockActivity.EXTRA_CONTROL_PLAY:
                    playClick();
                    break;
                case LockActivity.EXTRA_CONTROL_NEXT:
                    mTransportControls.skipToNext();
                    break;
                case LockActivity.EXTRA_CONTROL_PREV:
                    mTransportControls.skipToPrevious();
                    break;
            }
        }
    };

    /**
     * 根据id播放音乐
     *
     * @param musicId id
     */
    public void playMusicById(String musicId) {
        Log.i(LogHelper.INSTANCE.getTAG(), "playMusicById: id=" + musicId);
        if (mTransportControls != null) {
            mProvider.setPlayMusic(musicId);
            mTransportControls.skipToQueueItem(mProvider.getIndexFromPlayList(musicId));
        }
    }

    ;

    /**
     * 根据id播放音乐
     *
     * @param musicId id
     */
    public void playMusicByIdFromList(String musicId) {
        Log.i(LogHelper.INSTANCE.getTAG(), "playMusicById: id=" + musicId);
        if (mTransportControls != null) {
            mTransportControls.skipToQueueItem(mProvider.getIndexFromPlayList(musicId));
        }
    }

    /**
     * 播放音乐列表，并可以指定播放音乐id
     */
    public void playMusicList(final List<MusicModel> musicModels, final String startId) {
        // 子线程添加更多的歌曲
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                if (musicModels.equals(mProvider.getPlayList())) {
                    if (startId != null) {
                        playMusicByIdFromList(startId);
                    } else {
                        playMusicByIdFromList(musicModels.get(0).getId());
                    }
                    return;
                }
                mProvider.clearPlayList();
                for (MusicModel musicModel : musicModels) {
                    if (startId == null && musicModels.indexOf(musicModel) == 0) {
                        // 没有设置起始播放id,默认播放第一首
                        playMusicById(musicModels.get(0).getId());
                        continue;
                    }
                    if (startId == null || !startId.equals(musicModel.getId())) {
                        // 非指定的音乐只添加进列表
                        mProvider.setPlayMusic(musicModel.getId());
                        continue;
                    }
                    playMusicById(startId);
                }
            }
        });
    }

    /**
     * 删除音乐文件
     */
    public void deleteMusicFile(final MusicModel musicModel) {
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                while (mPlayList.contains(musicModel)) {
                    deletePlayListMusic(mPlayList.indexOf(musicModel));
                }
                SystemHelper.INSTANCE.deleteMusicFile(IndexActivity.this, new File(musicModel.getUrl()));
            }
        });
    }

    /**
     * 播放音乐列表，并开始播放第一首音乐
     */
    public void playMusicList(List<MusicModel> musicModels) {
        playMusicList(musicModels, null);
    }

    /**
     * 下一首播放
     *
     * @param musicId 音乐id
     */
    public void setNextPlayMusic(String musicId) {
        if (mState == PlaybackStateCompat.STATE_STOPPED) {
            playMusicById(musicId);
            return;
        }
        mProvider.setPlayMusic(musicId, MusicAudioService.Companion.getMCurrentPosition() + 1);
    }

    /**
     * 添加需要通知的歌曲适配器
     */
    public void setAdapter(MusicItemAdapter musicItemAdapter) {
        mAdapterList.add(musicItemAdapter);
    }

    /**
     * 设置背景色
     *
     * @param color 颜色
     */
    @Override
    public void setBgColor(int color) {
        mGetColor = color;
        if (mDialogBuilder == null) {
            return;
        }
        mDialogBuilder.setBgColor(mGetColor);
    }
}
